package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //创建专门处理订单的线程
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //预加载秒杀Lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //服务启动时就初始化订单处理器
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {//死循环
                try {
                    //1.获取队列中的订单信息
                    //take()：队列空了就阻塞，有订单才往下走。
                    VoucherOrder voucherOrder = orderTasks.take();
                    //2.创建订单
                    handleVoucherOrdrer(voucherOrder);
                } catch (InterruptedException e) {
                    log.error("订单处理异常");
                }

            }
        }
    }

    private void handleVoucherOrdrer(VoucherOrder voucherOrder) {
        //因为已经是一个新的线程，所以只能在订单里获取用户。
        //创建锁对象。兜底校验，
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁（无参表示失败立即重试）
        boolean isLock = lock.tryLock();
        //判断锁是否成功
        if(!isLock){
            //返回错误信息或重试
            log.error("不允许重复下单");
            return ;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }

    }
    private IVoucherOrderService proxy;
    /**
     *lua脚本判断购买资格，数据库执行业务
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //1.执行lua脚本.脚本里无key，传入空集合
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        // 2.判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1?"库存不足":"不能重复下单");
        }
        //2.2为0，有购买资格，把下单消息保存到阻塞队列
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id
        voucherOrder.setId(orderId);
        //订单券id
        voucherOrder.setVoucherId(voucherId);
        //用户id
        voucherOrder.setUserId(userId);
        //创建阻塞队列
        orderTasks.add(voucherOrder);
        //3.获取代理对象
         proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);

    }

//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//            //没有
//            return Result.fail("秒杀未开始");
//        }
//        //3.判断秒杀是否结束
//        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//            //没有
//            return Result.fail("秒杀已经结束");
//        }
//        //4.判断库存是否充足
//        if(seckillVoucher.getStock() < 1){
//            return Result.fail("该秒杀券已经抢完");
//        }
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象.并发下防止一人同时下单。当线程1成功在redis中存入数据后，key和value已经确定了，获取锁成功
//        // 此时线程2再进入相同的key后传入value，无法进行存入操作。
//        //SumpleRedisLock lock = new SumpleRedisLock("order:" + userId, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        //获取锁（无参表示失败立即重试）
//        boolean isLock = lock.tryLock();
//        //判断锁是否成功
//        if(!isLock){
//            //返回错误信息或重试
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            //获取代理对象
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        //6.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")//set stock =stock-1(where条件成功后执行的)
                .eq("voucher_id", voucherId).gt("stock", 0)//where id = ? and stock > 0
                .update();
            if (!success) {
                log.error("该秒杀券已经抢完");
            }
            //8.返回订单id
            save(voucherOrder);
    }
}